package cn.com.utils;


import cn.com.consts.MsgCd;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * 数据库util
 *
 * @author LiuGuodong
 * @date 2024/01/23
 */
public class DatabaseUtil {
    private static final String JDBC_DRIVER = "org.mariadb.jdbc.Driver";

    //private static final String DATABASE_URL = "jdbc:mariadb://10.106.6.31:30001/rightcloud?sslMode=required&useUnicode=true&autoReconnect=true&failOverReadOnly=false&characterEncoding=UTF-8&allowMultiQueries=true&useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=Asia/Shanghai";
    //private static final String USERNAME = "root";
    //private static final String PASSWORD = "nj116v9QoOCWN0Vy~";

    //private static final String DATABASE_URL = "jdbc:mariadb://10.106.6.38:32569/rightcloud?sslMode=required&useUnicode=true&autoReconnect=true&failOverReadOnly=false&characterEncoding=UTF-8&allowMultiQueries=true&useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=Asia/Shanghai";
    //private static final String USERNAME = "root";
    //private static final String PASSWORD = "vx7RsHeDXMj9XSXpV^Qe";

    private static final String DATABASE_URL = "jdbc:mariadb://10.182.0.108:30306/rightcloud?sslMode=required&useUnicode=true&autoReconnect=true&failOverReadOnly=false&characterEncoding=UTF-8&allowMultiQueries=true&useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=Asia/Shanghai";
    private static final String USERNAME = "test";
    private static final String PASSWORD = "vx7RsHeDXMj9XSXpV^Qe";

    // 加载 JDBC 驱动程序
    static {
        try {
            Class.forName(JDBC_DRIVER);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            throw new RuntimeException(WebUtil.getMessage(MsgCd.ERR_MSG_BSS_667490235));
        }
    }

    // 获取数据库连接
    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(DATABASE_URL, USERNAME, PASSWORD);
    }

    // 关闭数据库连接
    public static void closeConnection(Connection connection) {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        // 测试数据库连接
        try {
            Connection connection = DatabaseUtil.getConnection();
            if (connection != null) {
                System.out.println("Connected to the database!");
                // 在这里执行你的数据库操作
                // ...
                // 关闭连接
                DatabaseUtil.closeConnection(connection);
            } else {
                System.out.println("Failed to connect to the database!");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
